package com.nutstudio.nutbus.main;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.nutstudio.nutbus.R;
import com.nutstudio.nutbus.adpter.MainListAdapter;
import com.nutstudio.nutbus.adpter.SearchListAdapter;
import com.nutstudio.nutbus.base.NetActivity;
import com.nutstudio.nutbus.bean.LineHeaderBean;
import com.nutstudio.nutbus.config.LineInfo;
import com.nutstudio.nutbus.db.DBManager;
import com.nutstudio.nutbus.global.GlobalValue;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

public class MainActivity extends NetActivity {
    private static final int getLineInfoKey=3;
    @InjectView(R.id.toolbar)
    Toolbar toolbar;
    @InjectView(R.id.main_list_rv)
    RecyclerView mainListRv;
    @InjectView(R.id.content_main)
    RelativeLayout contentMain;
    @InjectView(R.id.fab)
    FloatingActionButton fab;
    private MainListAdapter listAdapter;
    private List<LineHeaderBean> list=new ArrayList<>();
    private RecyclerView searchRv;
    private EditText searchEt;
    private SearchListAdapter searchListAdapter;
    private List<LineHeaderBean> searchlist =new ArrayList<>();
    private DBManager dbManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.inject(this);
        dbManager=new DBManager(this);
        iRequest=getRequest();
        setSupportActionBar(toolbar);
        initData();
        initView();
    }

    private void initData() {
        String sql = "select  * from " + LineInfo.LINE_TABLE_NAME;
        List<LineHeaderBean> myList=dbManager.queryAlldata(sql);
        for (int i=0;i<myList.size();i++){
            list.add(0,myList.get(i));
        }
    }

    private boolean checkRepeat(String lineId){
        String sql = "select  * from " + LineInfo.LINE_TABLE_NAME+" where " + LineInfo.LINE_ID + " = '"
                + lineId + "'";
      List<LineHeaderBean> list1= dbManager.queryAlldata(sql);
        if (list1.size()>0){
            Toast.makeText(this,"已经添加过此线路",Toast.LENGTH_SHORT).show();
            return true;
        }else {
            return false;
        }
    }
    private void refreshListData(){
        list.clear();
        String sql = "select  * from " + LineInfo.LINE_TABLE_NAME;
        List<LineHeaderBean> myList=dbManager.queryAlldata(sql);
        for (int i=0;i<myList.size();i++){
            list.add(0,myList.get(i));
        }
        listAdapter.notifyDataSetChanged();
    }

    private void initView() {

        listAdapter=new MainListAdapter(this,list);
        LinearLayoutManager linearLayoutManager=new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mainListRv.setLayoutManager(linearLayoutManager);
        mainListRv.setAdapter(listAdapter);
        listAdapter.setOnItemClickLitener(new MainListAdapter.OnItemClickLitener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent=new Intent(MainActivity.this,ShowLineActivity.class);
                intent.putExtra("id",list.get(position).getLineId());
                intent.putExtra("name",list.get(position).getLineName());
                startActivityForResult(intent,1);
            }

            @Override
            public void onItemLongClick(View view, final int position) {
                AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("删除线路");
                String startStation="";
                String endStation="";
                if (list.get(position).getStartStation()!=null&&list.get(position).getStartStation().length()>0){
                     startStation=list.get(position).getStartStation();
                }
                if (list.get(position).getEndStation()!=null&&list.get(position).getEndStation().length()>0){
                     endStation=list.get(position).getEndStation();
                }
                builder.setMessage("确定要删除线路："+startStation+"→"+endStation);
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dbManager.deleteSingle(list.get(position).getLineId());
                        refreshListData();
                    }
                });
                builder.setNegativeButton("取消",null);
                builder.show();
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @OnClick(R.id.fab)
    public void onClick() {
       showSearchDialog();
    }

    @Override
    public void responseSuccess(String str, int whichCall) {
        if (whichCall==getLineInfoKey){
            try {
                JSONArray jsonArray=new JSONArray(str);
                if (jsonArray.length()>0){
                    searchlist.clear();
                    for (int i=0;i<jsonArray.length();i++){
                        JSONObject object=jsonArray.getJSONObject(i);
                        LineHeaderBean lineHeaderBean=new LineHeaderBean();
                        lineHeaderBean.setLineId(object.getString("ROUTEID"));
                        lineHeaderBean.setLineName(object.getString("ROUTENAME"));
                        lineHeaderBean.setSelect(false);
                        searchlist.add(lineHeaderBean);
                    }
                    searchListAdapter.notifyDataSetChanged();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode==1&&resultCode==2){
            LineHeaderBean headerBean=new LineHeaderBean();
            headerBean.setLineId(data.getExtras().getString(LineInfo.LINE_ID));
            headerBean.setLineName(data.getExtras().getString(LineInfo.LINE_NAME));
            headerBean.setStartStation(data.getExtras().getString(LineInfo.START_STATION_NAME));
            headerBean.setEndStation(data.getExtras().getString(LineInfo.END_STATION_NAME));
            headerBean.setStartTime(data.getExtras().getString(LineInfo.START_TIME));
            headerBean.setEndTime(data.getExtras().getString(LineInfo.END_TIME));
            headerBean.setNormalValue(data.getExtras().getString(LineInfo.LINE_VALUE));
            Log.d("tetst",headerBean.getEndStation()+""+headerBean.getLineId());
           dbManager.updatesingle(headerBean);
            refreshListData();
        }
    }

    private void showSearchDialog(){
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setTitle("添加站点");
        View view= LayoutInflater.from(this).inflate(R.layout.add_lin_dialog_layout,null);
        view.findViewById(R.id.search_tv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
        searchEt=(EditText)view.findViewById(R.id.input_et);
        searchRv=(RecyclerView)view.findViewById(R.id.list_rv);
        searchListAdapter=new SearchListAdapter(this, searchlist);
        LinearLayoutManager linearLayoutManager=new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        searchRv.setLayoutManager(linearLayoutManager);
        searchRv.setAdapter(searchListAdapter);
        builder.setView(view);
        builder.show();
        searchListAdapter.setOnItemClickLitener(new SearchListAdapter.OnItemClickLitener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent=new Intent(MainActivity.this,ShowLineActivity.class);
                intent.putExtra("id",searchlist.get(position).getLineId());
                intent.putExtra("name",searchlist.get(position).getLineName());
                Log.d("id12",searchlist.get(position).getLineId());
                startActivityForResult(intent,1);
            }

            @Override
            public void onColoctionClick(View view, int pos) {
                if (!checkRepeat(searchlist.get(pos).getLineId())){
                    dbManager.addsingle(searchlist.get(pos));
                    LineHeaderBean headerBean=searchlist.get(pos);
                    headerBean.setSelect(true);
                    searchlist.set(pos,headerBean);
                    searchListAdapter.notifyItemChanged(pos);
                    refreshListData();
                }

            }

            @Override
            public void onItemLongClick(View view, int position) {

            }
        });
        searchEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.length()>0){
                    String url= GlobalValue.searchLine+charSequence;
                    iRequest.getJsonObjRequestNot(url,getLineInfoKey);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }
}
